from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import jwt

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'secret_key' # 用于生成 token 的密钥
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

@app.route('/register', methods=['POST'])
def register():
    req_data = request.get_json()
    username = req_data.get('username')
    password = req_data.get('password')
    if not username or not password:
        return jsonify({'status': 'fail', 'message': '用户名和密码不能为空！'}), 400
    user = User.query.filter_by(username=username).first()
    if user:
        return jsonify({'status': 'fail', 'message': '失败！该用户已经存在！'}), 400
    new_user = User(username=username, password=password)
    db.session.add(new_user)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '注册成功！'}), 200

@app.route('/login', methods=['POST'])
def login():
    req_data = request.get_json()
    username = req_data.get('username')
    password = req_data.get('password')
    if not username or not password:
        return jsonify({'status': 'fail', 'message': '用户名和密码不能为空！'}), 400
    user = User.query.filter_by(username=username, password=password).first()
    if not user:
        return jsonify({'status': 'fail', 'message': '用户名或者密码错误！'}), 401
    token = jwt.encode({'username': username}, app.config['SECRET_KEY'], algorithm='HS256')
    return jsonify({'status': 'success', 'message': 'Logged in successfully', 'access_token': token}), 200

if __name__ == '__main__':
    with app.app_context(): # 添加 app 上下文
        db.create_all()
    app.run()